/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <RongIMKit/RongIMKit.h>
#import "AFNetworking.h"
#import "GeTuiSdk.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
#import "NSString+Tool.h"
#import "RootViewController.h"
#import "NavViewController.h"
#import <React/RCTLinkingManager.h>
//#import <SobotKit/SobotKit.h>

//#import <Bugly/Bugly.h>


#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

@interface AppDelegate () <UIApplicationDelegate,UNUserNotificationCenterDelegate,GeTuiSdkDelegate,RCIMUserInfoDataSource,RCIMGroupInfoDataSource,RCIMGroupUserInfoDataSource>

@property (nonatomic,strong)AFHTTPSessionManager *manager;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  
  // @{@"flag":@"one"}
  NSURL *jsCodeLocation;
  
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
  // NSLog(@"==%@",jsCodeLocation);
  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"PeitaMerchants"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  RootViewController *rootVC = [[RootViewController alloc] init];
  rootVC.view = rootView;
//  _nav = [[UINavigationController alloc] initWithRootViewController:rootVC];
//  [_nav setNavigationBarHidden:YES];
  NavViewController *nav = [[NavViewController alloc] initWithRootViewController:rootVC];
  self.window.rootViewController = nav;
  [self.window makeKeyAndVisible];
  
  
  //******************个推*************************
  //通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
  [GeTuiSdk startSdkWithAppId:GTAPPID appKey:GTAPPKEY appSecret:GTAPPSECRET delegate:self];
  
  [self registerUserNotification];
  // ******************智齿客服*************************
  
  //  [[ZCLibClient getZCLibClient] setAppKey:ZC_APPKEY];
  //
  //  [ZCLibClient getZCLibClient].autoNotification = YES;
  
  // ******************Bugly*************************
  //  [Bugly startWithAppId:BUGLYID];
  
  
  self.manager = [AFHTTPSessionManager manager];
  self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  
  [[RCIM sharedRCIM] initWithAppKey:RCAPPKEY];
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectRC:) name:@"connectRC" object:nil];
  
  [[RCIM sharedRCIM] setUserInfoDataSource:self];
  [[RCIM sharedRCIM] setGroupInfoDataSource:self];
  [[RCIM sharedRCIM] setGroupUserInfoDataSource:self];
  
  /**
   * 统计推送打开率1
   */
  [[RCIMClient sharedRCIMClient] recordLaunchOptionsEvent:launchOptions];
  NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromLaunchOptions:launchOptions];
  if (pushServiceData) {
    
    NSLog(@"该启动事件包含来自融云的推送服务");
    for (id key in [pushServiceData allKeys]) {
      NSLog(@"%@", pushServiceData[key]);
    }
  } else {
    
    NSLog(@"该启动事件不包含来自融云的推送服务");
  }
  
  [[NSNotificationCenter defaultCenter]
   addObserver:self
   selector:@selector(didReceiveMessageNotification:)
   name:RCKitDispatchMessageNotification
   object:nil];
  
  return YES;
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

- (void)connectRC:(NSNotification *)connectRCNot {
  
  NSMutableDictionary *dict = [connectRCNot object];
  
  
  [self.manager GET:[NSString stringWithFormat:GET_TOKEN,dict[@"accessToken"]] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSString *string = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
    
    NSDictionary *tokenDict = [string dictionaryWithJsonString];
    NSString *tokenString = tokenDict[@"token"];
    
    NSLog(@"获取的token:%@",tokenString);
    
    [[NSUserDefaults standardUserDefaults] setObject:tokenString forKey:@"token"];
    
    if (tokenString.length == 0) {
      
    } else {
      
      if ([[RCIM sharedRCIM] getConnectionStatus] == ConnectionStatus_Connected) {
        
      } else {
        
        dispatch_async(dispatch_get_main_queue(), ^{
          
          [[RCIM sharedRCIM] connectWithToken:tokenString success:^(NSString *userId) {
            
            NSLog(@"连接成功:%@",userId);
            
          } error:^(RCConnectErrorCode status) {
            
            NSLog(@"错误啦:%ld",(long)status);
            
          } tokenIncorrect:^{
            
          }];
          
        });
      }
      
    }
    
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
    NSLog(@"这个错误啦:%@",[error localizedDescription]);
  }];
  
  if (![dict[@"userIcon"] isKindOfClass:[NSNull class]] || [dict[@"userIcon"] length] != 0) {
    
          RCUserInfo *userInfo = [[RCUserInfo alloc] initWithUserId:[NSString stringWithFormat:@"%@",dict[@"userId"]] name:dict[@"userName"] portrait:[NSString stringWithFormat:@"%@/%@",HOME_DETAIL_COMMON_BASE_URL,dict[@"userIcon"]]];
          [RCIM sharedRCIM].currentUserInfo = userInfo;

      }

}

/** 注册用户通知 */
- (void)registerUserNotification {
  
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
      if (!error) {
        NSLog(@"request authorization succeeded!");
      }
    }];
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
    UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
  } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
    UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  } else {
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                   UIRemoteNotificationTypeSound |
                                                                   UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
  }
}

//禁止横屏
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
  return UIInterfaceOrientationMaskPortrait;
}

// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  
  // 将收到的APNs信息传给个推统计
  [GeTuiSdk handleRemoteNotification:userInfo];
  // 处理APN
  NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
  completionHandler(UIBackgroundFetchResultNewData);
  
  
  //  NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
  //  NSString *timeStr = [NSString stringWithFormat:@"%.0f",time];
  
  //    NSLog(@"=====%@",userInfo[@"aps"][@"alert"][@"body"]);
}

/**
 * 推送处理2
 */
//注册用户通知设置
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [application registerForRemoteNotifications];
}

/** SDK启动成功返回cid */
//上传cid
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
  // [4-EXT-1]: 个推SDK已注册，返回clientId
  NSLog(@"\n>>>[个推返回成功 RegisterClient]:%@\n\n", clientId);
  
  [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"clientID"];
  
}

/**
 * 推送处理3
 */
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSString *token =
  [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                         withString:@""]
    stringByReplacingOccurrencesOfString:@">"
    withString:@""]
   stringByReplacingOccurrencesOfString:@" "
   withString:@""];
  
  [[RCIMClient sharedRCIMClient] setDeviceToken:token];
  
  // [3]:向个推服务器注册deviceToken
  [GeTuiSdk registerDeviceToken:token];
  // 向智齿客服注册
  NSLog(@"[个推token:]%@,,,,,%@",deviceToken,token);
  //  [[ZCLibClient getZCLibClient] setToken:deviceToken];
  
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}


//******************************个推*******************************
#pragma mark - GeTuiSdkDelegate
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  /// Background Fetch 恢复SDK 运行
  [GeTuiSdk resume];
  completionHandler(UIBackgroundFetchResultNewData);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  
  NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
  
  // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  
  NSLog(@"点击进入通知:didReceiveNotification：%@", response.notification.request.content.userInfo);
  NSDictionary *pushDictionary = response.notification.request.content.userInfo;
  
  // [ GTSdk ]：将收到的APNs信息传给个推统计
  [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
  completionHandler();
  
  if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
  } else {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  }
  
}

#endif

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
  // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
  NSLog(@"\n>>>[个推出错 error]:%@\n\n", [error localizedDescription]);
}

/**
 *  字符串转字典
 *
 *  @return 字典
 */
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
  
  if (!jsonString) {
    return nil;
  }
  
  NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                        
                                                       options:NSJSONReadingMutableContainers
                        
                                                         error:&err];
  
  if(err) {
    
    return nil;
    
  }
  
  return dict;
  
}


//* SDK收到透传消息回调
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
  // [4]: 收到个推消息
  NSString *payloadMsg = nil;
  if (payloadData) {
    payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    
    NSDictionary *payloadDict = [self dictionaryWithJsonString:payloadMsg];
    
  }
  
  NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
  NSLog(@"\n>>>[收到个推消息 ReceivePayload]:%@\n\n", msg);
  
  //    [UIApplication sharedApplication].applicationIconBadgeNumber =
  //    [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
}

//* SDK收到sendMessage消息回调
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
  // [4-EXT]:发送上行消息结果反馈
  NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
  NSLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
  
}

//* SDK运行状态通知
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
  // [EXT]:通知SDK运行状态
  NSLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
}

//* SDK设置推送模式回调
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
  if (error) {
    NSLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
    return;
  }
  NSLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}


/**
 * 推送处理4
 * userInfo内容请参考官网文档
 */
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
  
  //************************融云***********************************
  /**
   * 统计推送打开率2
   */
  [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
  /**
   * 获取融云推送服务扩展字段2
   */
  NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromRemoteNotification:userInfo];
  if (pushServiceData) {
    NSLog(@"该远程推送包含来自融云的推送服务");
    for (id key in [pushServiceData allKeys]) {
      NSLog(@"key = %@, value = %@", key, pushServiceData[key]);
    }
  } else {
    NSLog(@"该远程推送不包含来自融云的推送服务");
  }
  
  //************************融云***********************************
  application.applicationIconBadgeNumber = 0; // 标签
  NSLog(@"\n>>>:[Receive RemoteNotification]:%@\n\n", userInfo);
  
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
  
  //************************融云***********************************
  /**
   * 统计推送打开率3
   */
  [[RCIMClient sharedRCIMClient] recordLocalNotificationEvent:notification];
  //************************融云***********************************
  
}

//******************************融云*******************************
- (void)applicationDidEnterBackground:(UIApplication *)application {
  
  int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                       @(ConversationType_PRIVATE),
                                                                       @(ConversationType_DISCUSSION),
                                                                       @(ConversationType_APPSERVICE),
                                                                       @(ConversationType_PUBLICSERVICE),
                                                                       @(ConversationType_GROUP)
                                                                       ]];
  application.applicationIconBadgeNumber = unreadMsgCount;
  
}

- (void)redirectNSlogToDocumentFolder {
  
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask, YES);
  NSString *documentDirectory = [paths objectAtIndex:0];
  
  NSDate *currentDate = [NSDate date];
  NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
  [dateformatter setDateFormat:@"MMddHHmmss"];
  NSString *formattedDate = [dateformatter stringFromDate:currentDate];
  
  NSString *fileName = [NSString stringWithFormat:@"rc%@.log", formattedDate];
  NSString *logFilePath =
  [documentDirectory stringByAppendingPathComponent:fileName];
  
  freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
          stdout);
  freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
          stderr);
}

- (void)didReceiveMessageNotification:(NSNotification *)notification {
  RCMessage *message = notification.object;
  if (message.messageDirection == MessageDirection_RECEIVE) {
    [UIApplication sharedApplication].applicationIconBadgeNumber =
    [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
  }
}


#pragma mark - RCWKAppInfoProvider
- (NSString *)getAppName {
  return @"融云";
}

- (NSString *)getAppGroups {
  return @"group.com.RCloud.UIComponent.WKShare";
}

- (void)openParentApp {
  [[UIApplication sharedApplication]
   openURL:[NSURL URLWithString:@"rongcloud://connect"]];
}

- (BOOL)getNewMessageNotificationSound {
  return ![RCIM sharedRCIM].disableMessageAlertSound;
}

- (void)setNewMessageNotificationSound:(BOOL)on {
  [RCIM sharedRCIM].disableMessageAlertSound = !on;
}

#pragma mark - RCIMConnectionStatusDelegate
- (void)dealloc {
  [[NSNotificationCenter defaultCenter]
   removeObserver:self
   name:RCKitDispatchMessageNotification
   object:nil];
  
}


// 群组信息提供者
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion {
  
  RCGroup *group = [[RCGroup alloc] init];
  group.groupId = groupId;
  
  [[ACHLHttpRequestTool shareHttpRequestTool] getWithURL:[NSString stringWithFormat:CROWD_DETAIL,[[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"],groupId] params:nil success:^(NSNumber *code, NSString *msg, NSDictionary *data) {
    
    if ([code isEqualToNumber:@10000]) {
      
      if (!data) {
        
        completion(nil);
      } else {
        group.groupName = data[@"name"];
        group.portraitUri = [NSString stringWithFormat:@"%@/%@",HOME_DETAIL_COMMON_BASE_URL,data[@"group_img"]];
        
        completion(group);
      }
      
    } else {
      
      completion(nil);
    }
  } failure:^(NSError *error) {
    
  }];
  
}

// 用户信息
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
  
  RCUserInfo *user = [[RCUserInfo alloc] init];
  
  user.userId = userId;
  
  [[ACHLHttpRequestTool shareHttpRequestTool]getWithURL:[NSString stringWithFormat:USERINFO_URL,[[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"],userId] params:nil success:^(NSNumber *code, NSString *msg, NSDictionary *data) {
    if ([code isEqualToNumber:@10000]) {
      if ([data isKindOfClass:[NSNull class]]) {
        
        completion(nil);
      } else {
        
        if (!data[@"user_head_img"]) {
          
        } else {
          user.portraitUri = [NSString stringWithFormat:@"%@/%@",HOME_DETAIL_COMMON_BASE_URL,[NSString stringWithFormat:@"%@",data[@"user_head_img"]]];
        }
        
        user.name = [NSString stringWithFormat:@"%@",[data objectForKey:@"username"]];
        
        completion(user);
        
      }
      
    } else {
      completion(nil);
    }
    
  } failure:^(NSError *error) {
    
  }];
  
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
  // 进入前台
  [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}



@end
